/* -*-  Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2010 University College London 
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Author: Joao Taveira Araujo <j.araujo@ucl.ac.uk>
 */

#include <vector>
#include "ns3/log.h"
#include "ns3/ptr.h"
#include "ns3/names.h"
#include "ns3/node.h"
#include "ns3/ipv4.h"
#include "ns3/ipv4-route.h"
#include "ns3/ipv4-list-routing.h"
#include "ns3/assert.h"
#include "ns3/config.h"
#include "ns3/ipv4-address.h"
#include "ns3/ipv4-routing-protocol.h"
#include "ns3/point-to-point-net-device.h"
#include "ns3/queue.h"
#include "ns3/ppp-header.h"
#include "ipv4-react-routing-helper.h"

NS_LOG_COMPONENT_DEFINE("Ipv4ReactRoutingHelper");

namespace ns3 {

Ipv4ReactRoutingHelper::Ipv4ReactRoutingHelper()
{
  m_agentFactory.SetTypeId("ns3::Ipv4ReactRouting");
}


Ipv4ReactRoutingHelper::Ipv4ReactRoutingHelper (const Ipv4ReactRoutingHelper &o)
  : m_agentFactory (o.m_agentFactory)
{
}

Ipv4ReactRoutingHelper* 
Ipv4ReactRoutingHelper::Copy (void) const 
{
  return new Ipv4ReactRoutingHelper (*this); 
}

Ptr<Ipv4RoutingProtocol> 
Ipv4ReactRoutingHelper::Create (Ptr<Node> node) const
{
  return m_agentFactory.Create<Ipv4ReactRouting> ();
}

Ptr<Ipv4ReactRouting>
Ipv4ReactRoutingHelper::GetReactRouting (Ptr<Ipv4> ipv4) const
{
  NS_LOG_FUNCTION (this);
  Ptr<Ipv4RoutingProtocol> ipv4rp = ipv4->GetRoutingProtocol ();
  NS_ASSERT_MSG (ipv4rp, "No routing protocol associated with Ipv4");
  if (DynamicCast<Ipv4ReactRouting> (ipv4rp))
    {
      NS_LOG_LOGIC ("React routing found as the main IPv4 routing protocol.");
      return DynamicCast<Ipv4ReactRouting> (ipv4rp); 
    } 
  if (DynamicCast<Ipv4ListRouting> (ipv4rp))
    {
      Ptr<Ipv4ListRouting> lrp = DynamicCast<Ipv4ListRouting> (ipv4rp);
      int16_t priority;
      for (uint32_t i = 0; i < lrp->GetNRoutingProtocols ();  i++)
        {
          NS_LOG_LOGIC ("Searching for react routing in list");
          Ptr<Ipv4RoutingProtocol> temp = lrp->GetRoutingProtocol (i, priority);
          if (DynamicCast<Ipv4ReactRouting> (temp))
            {
              NS_LOG_LOGIC ("Found react routing in list");
              return DynamicCast<Ipv4ReactRouting> (temp);
            }
        }
    }
  NS_LOG_LOGIC ("React routing not found");
  return 0;
}

void
Ipv4ReactRoutingHelper::EnableAscii (std::string prefix, NodeContainer n)
{
  NS_LOG_FUNCTION(this);
  for (NodeContainer::Iterator i = n.Begin (); i != n.End (); ++i)
  {
    Ptr<Node> node = *i;
    EnableAsciiInternal (prefix, node);
  }
}

void 
Ipv4ReactRoutingHelper::EnableAsciiInternal (std::string prefix, Ptr<Node> nd)
{
  NS_LOG_FUNCTION(this);
  Ptr<Ipv4> ipv4 = nd->GetObject<Ipv4>();
  Ptr<Ipv4ReactRouting> routingProtocol = GetReactRouting (ipv4);

  std::string newPrefix, filename;


  AsciiTraceHelper asciiTraceHelper;
  // log stats (loss calculations, flowSplit)
  if(routingProtocol)
  {
    std::string newPrefix = prefix+"-stat";
    std::string filename = asciiTraceHelper.GetFilenameFromNode (newPrefix, nd);

    Ptr<OutputStreamWrapper> stream = asciiTraceHelper.CreateFileStream (filename);
    routingProtocol->TraceConnectWithoutContext("UpdatePref", MakeBoundCallback (&Ipv4ReactRoutingHelper::DefaultUpdateFlowSplit,stream));
  }

  newPrefix = prefix+"-out";
  filename = asciiTraceHelper.GetFilenameFromNode (newPrefix, nd);

  Ptr<OutputStreamWrapper> stream = asciiTraceHelper.CreateFileStream (filename);
  ipv4->TraceConnectWithoutContext("UnicastForward", MakeBoundCallback (&Ipv4ReactRoutingHelper::ReflexForward,stream));
}

void
Ipv4ReactRoutingHelper::TraceQueue (std::string prefix, NodeContainer n)
{
  NS_LOG_FUNCTION(this);
  for (NodeContainer::Iterator i = n.Begin (); i != n.End (); ++i)
  {
    Ptr<Node> node = *i;
    TraceQueueInternal (prefix, node);
  }
}


void 
Ipv4ReactRoutingHelper::TraceQueueInternal (std::string prefix, Ptr<Node> nd)
{
  NS_LOG_FUNCTION(this);
  
  for (uint32_t i = 1; i < nd->GetNDevices (); i++)
    {
       Ptr<PointToPointNetDevice> ppnd = DynamicCast<PointToPointNetDevice>(nd->GetDevice(i));
       Ptr<Queue> qnd = ppnd->GetQueue();

       std::string newPrefix, filename;


        AsciiTraceHelper asciiTraceHelper;
        // log stats (loss calculations, flowSplit)

        newPrefix = prefix+"-drop";
        filename = asciiTraceHelper.GetFilenameFromInterfacePair (newPrefix, nd, i);

        Ptr<OutputStreamWrapper> stream = asciiTraceHelper.CreateFileStream (filename);
         bool tes = qnd->TraceConnectWithoutContext("Drop", MakeBoundCallback (&Ipv4ReactRoutingHelper::QueueDrop,stream));
        NS_ASSERT(tes);
      }
}

void
Ipv4ReactRoutingHelper::DefaultUpdateFlowSplit (Ptr<OutputStreamWrapper> stream, Ptr<Ipv4ReactTableEntry> p)
{
  NS_LOG_FUNCTION (stream << p);
  *stream->GetStream () << " " << p->GetDestNetwork() << " " << p->GetInterface() << " " \
                  << Simulator::Now ().GetMilliSeconds () << " " << p->GetFlowSplit() << " " << p->GetWghtLoss() << " " << p->GetInstTxmit() << " " << p->GetInstRexmit() << std::endl;
}

void
Ipv4ReactRoutingHelper::ReflexForward (Ptr<OutputStreamWrapper> stream, const Ipv4Header &header, Ptr<const Packet> p, uint32_t interface)
{
  NS_LOG_FUNCTION (stream << p);

  uint32_t reflex = header.GetFlags() & Ipv4Header::RESERVED_BIT;
  reflex += header.GetTos(Ipv4Header::ECN_MASK);

  *stream->GetStream() << interface << " "  << Simulator::Now().GetTimeStep() << " " << reflex << " " <<  p->GetSize() << '\n';
}

void
Ipv4ReactRoutingHelper::QueueDrop (Ptr<OutputStreamWrapper> stream, Ptr<const Packet> p)
{
  NS_LOG_FUNCTION (stream << p);

  Ipv4HeaderPathTag tag;
  uint32_t dscp = 0;
  bool found = p->PeekPacketTag(tag);

  if ( found ) {
    dscp = tag.GetPath();
  }

  *stream->GetStream() << dscp << " "  << Simulator::Now().GetTimeStep() << " " <<  p->GetSize() << '\n';
}

void
Ipv4ReactRoutingHelper::SetAttribute (std::string name, const AttributeValue &value)
{
  m_agentFactory.Set (name, value);
}
}; // namespace ns3
